import * as THREE from '../../build/three.module.js';
import Stats from '../../jsm/libs/stats.module.js';
import { GLTFLoader } from '../../jsm/loaders/GLTFLoader.js';

// 鼠标位置
let mouseX = 0, mouseY = 0;

const halfWindowWidth = innerWidth / 2, halfWindowHeight = innerHeight / 2;

// 网格对象
let mesh;

// 场景
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x060708);

// 相机
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 1, 10000);
camera.position.z = 1200;

// 光照
// 半球光做环境光
scene.add( new THREE.HemisphereLight(0x44333, 0x111122) );
// 聚光灯投射阴影
const spotL = new THREE.SpotLight(0xfffffb, 2);
spotL.position.set(0.5, 0, 1);
spotL.position.multiplyScalar(700);
scene.add(spotL);
// 设置聚光灯属性
spotL.castShadow = true;
spotL.shadow.mapSize.width = 2048;
spotL.shadow.mapSize.height = 2048;
spotL.shadow.camera.near = 200;
spotL.shadow.camera.fov = 40;
spotL.shadow.bias = -0.005;

// 白模贴图
const mapHeight = new THREE.TextureLoader().load('../../models/gltf/LeePerrySmith/Infinite-Level_02_Disp_NoSmoothUV-4096.jpg');
const material = new THREE.MeshPhongMaterial({
  color: 0x552811,
  specular: 0x222222,
  shininess: 25,
  bumpMap: mapHeight,
  bumpScale: 12
});

// 异步创建网格提
const buildMesh = (geo, scale, mal) => {
  mesh = new THREE.Mesh(geo, mal);

  mesh.position.y = -50;
  mesh.scale.set(scale, scale, scale);
  
  mesh.caseShadow = true;
  mesh.receiveShadow = true;

  scene.add(mesh);
}

// 模型几何体
const loader = new GLTFLoader();
loader.load('../../models/gltf/LeePerrySmith/LeePerrySmith.glb', gltf => {
  buildMesh(gltf.scene.children[0].geometry, 100, material);
});

// 渲染器
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
renderer.shadowMap.enabled = true;

// 统计
const stats = new Stats();
document.body.appendChild(stats.dom);

// 事件处理
// window Resize 事件
const handleWindowResize = () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();

  renderer.setSize(innerWidth, innerHeight);
}
// 鼠标移动
const handleMousemove = e => {
  mouseX = e.clientX - halfWindowWidth;
  mouseY = e.clientY - halfWindowHeight;
}

window.addEventListener('resize', handleWindowResize, false);
document.addEventListener('mousemove', handleMousemove, false);

// 渲染函数
const render = () => {
  const targetX = mouseY * 0.001;
  const targetY = mouseX * 0.001;

  if (mesh) {
    mesh.rotation.y += 0.05 * (targetY - mesh.rotation.y);
    mesh.rotation.x += 0.05 * (targetX - mesh.rotation.x);
  }

  renderer.render(scene, camera);
}

// 驱动函数
const animate = () => {
  requestAnimationFrame(animate);

  stats.update();
  render();
}
animate();